//
//  ZHLoginViewController.swift
//  weibosina
//
//  Created by zhangzhen on 16/6/15.
//  Copyright © 2016年 zhangzhen. All rights reserved.
//

import UIKit

class ZHLoginViewController: UIViewController {
    //懒加载webView
    private lazy var webView = UIWebView()

    override func viewDidLoad() {
        super.viewDidLoad()
        //设置左边的按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "didClickBackLoginButton:")

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
     }

    override func loadView() {
        //加载webView
        view = webView
        //设置webView的代理
        webView.delegate = self
        let request = NSURLRequest(URL: ZHNetWorkTools.sharetools.ouauthURL)
        webView .loadRequest(request)
        
    }
   //按钮点击方法
    @objc private func didClickBackLoginButton(sender:UIBarButtonItem) -> () {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
   //自动填充
    @objc private func autoFill() {
        
        let js = "document.getElementById('userId').value = '1019021088@qq.com';" +
        "document.getElementById('passwd').value = 'zz194112';"
        
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
        
        
    }


}
// MARK - webView的代理方法
extension ZHLoginViewController:UIWebViewDelegate{
    //
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        //1.找到对应回调为百度的网址
        guard let url = request.URL where url.host == "www.baidu.com" else{
            //其他请求不进行任何操作
            return true
        }
        //2.获取OAuth授权码
        guard let query = url.query where query.hasPrefix("code=") else{
            print("取消授权")
            return false
        }
        
        //3.提取授权码
//        print(query)
        let code = query.substringFromIndex("code=".endIndex)
//        print("授权码是 " +  (code));
        
        //4.获取accessToken,并且请求用户数据
        ZHUserAccountViewModel.shareUserAccount.loadAccessToken(code) { (isSuccessed) in
            print(isSuccessed)
            
        }
        return false
    }
}
